
from django.shortcuts import render,redirect
from app01 import models

from app01.utilss.forms import UserModelForm



def user_list(request):
    queryset = models.UserInfo.objects.all()
    # for obj in queryset:
    #     print(obj.id,obj.name,obj.depart.title,obj.password,obj.get_gender_display(),obj.create_time.strftime('%Y-%m-%d %H:%M:%S') )#处理性别和时间,通过id自动去关联的表中获取相应的数据
    return render(request, 'user_list.html', {'queryset': queryset})



def user_add(request):
    """添加用户"""
    if request.method == 'GET':
        form = UserModelForm()
        return render(request, 'user_add.html', {'form': form})
    form = UserModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect('/user/list/')
    else:
        return render(request, 'user_add.html', {'form': form})

def user_edit(request,nid):
    row_object = models.UserInfo.objects.filter(id=nid).first()
    if request.method == 'GET':
        form = UserModelForm(instance=row_object)
        return render(request, 'user_edit.html', {'form': form})
    form = UserModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/user/list/')
    else:
        return render(request, 'user_edit.html', {'form': form})

def user_delete(request):
    """删除用户"""
    nid = request.GET.get('nid')
    models.UserInfo.objects.filter(id=nid).delete()
    return redirect('/user/list/')